# -*- coding:utf-8 -*-
from PIL import ImageFont, Image, ImageDraw
import io, ddddocr, requests, re, os
from fontTools.ttLib import TTFont


class Spider_Data(object):
    def __init__(self):
        self.url = "https://www.shixiseng.com/interns?keyword=python&city=%E5%85%A8%E5%9B%BD&type=intern"
        self.ocr = ddddocr.DdddOcr()
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.43"
        }
        if not os.path.exists("实习僧反爬"):
            os.mkdir("实习僧反爬")

    def get_data_index(self):
        response = requests.get(url=self.url, headers=self.headers)
        return response.text

    def get_font_index(self, response):
        font_url = "https://www.shixiseng.com" + re.search(r'url\((.*?)\);}', response).group(1)
        resp = requests.get(font_url).content
        with open("./实习僧反爬/" + "file.woff", "wb") as f:
            f.write(resp)

        font = TTFont("./实习僧反爬/file.woff")
        # 获取加密之后的字体
        font_list = font.getGlyphOrder()[2:]
        return font_list

    # 代码直接复制就可以
    def parse_font_list(self, txt):
        img_size = 1024
        img = Image.new("1", (img_size, img_size), 255)
        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype("./实习僧反爬/file.woff", int(img_size * 0.7))
        txt = chr(txt)
        x, y = draw.textsize(txt, font=font)
        draw.text(((img_size - x) // 2, (img_size - y) // 2), txt, font=font, fill=0)
        return img

    """识别字体"""

    def font_analysis(self):
        font_old_list = []
        font_new_list = []
        f = TTFont("./实习僧反爬/file.woff")
        for i, glyp in f.getBestCmap().items():
            pil = self.parse_font_list(i)
            bytes_to = io.BytesIO()
            pil.save(bytes_to, format="PNG")
            res = self.ocr.classification(bytes_to.getvalue())
            font_old_list.append(i)
            font_new_list.append(res)
        font_list = list(zip(font_old_list[1:], font_new_list[1:]))
        font_data_dict = {}
        for font in font_list:
            hex_data = hex(font[0])
            font_data_dict[hex_data] = font[1]
        # 最终识别的字体
        return font_data_dict

    def replace_response(self, response, new_font_dict):
        resp = response.replace("&#", str(0))
        for key_data, value_data in new_font_dict.items():
            resp = re.sub(key_data, value_data, resp)
        print(resp)

    def main(self):
        response = self.get_data_index()
        old_font_list = self.get_font_index(response)
        new_font_list = self.font_analysis()
        self.replace_response(response, new_font_list)


if __name__ == '__main__':
    spider = Spider_Data()
    spider.main()
